package com.tn.cron;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.tn.bo.Invoice;
import com.tn.dao.InvoiceDAO;

/**
 * 
 * @author Amit Modi
 * 
 */
public class PaymentReportGenerator extends HttpServlet {
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		String companyUniqueIdentifier = req
				.getParameter(PaymentReportTaskGenerator.COMPANY_UNIQUE_ID);
		String companyId = req
				.getParameter(PaymentReportTaskGenerator.COMPANY_ID);
		System.out.println("Company Unique Identifier => "
				+ companyUniqueIdentifier);
		System.out.println("Company ID => " + companyId);
		this.generateReport(companyId, companyUniqueIdentifier);
	}

	private void generateReport(String companyId, String companyUniqueId) {
		System.out.println("Invoices Due for company id: " + companyId);
		// the method will be responsible for generating the report for the
		// company.
		GregorianCalendar cal = new GregorianCalendar();
		cal.set(Calendar.HOUR_OF_DAY, 0);
		cal.set(Calendar.MINUTE, 0);
		cal.set(Calendar.SECOND, 0);
		cal.set(Calendar.MILLISECOND, 0);
		Date currentDate = cal.getTime();
		InvoiceDAO iDao = new InvoiceDAO();
		// the better approach is to find list with invoice status, accepted
		// (but not yet paid) TODO
		List<Invoice> invoicesReceived = iDao.fetchInvoicesReceived(companyId);
		HashMap<String, List<Invoice>> invoicesMap = new HashMap<String, List<Invoice>>(); 
		for (Invoice invoice : invoicesReceived) {
			// here the condition should be added so that which invoices to be
			// considered in the report.
			Date expectedPaymentDate = invoice.getExpectedPaymentDate();
			if (null == expectedPaymentDate
					|| expectedPaymentDate.before(currentDate)) {
				String supplierCompnay = invoice.getMainSupplierCompnay();
				List<Invoice> list = invoicesMap.get(supplierCompnay);
				if(null == list){
					list = new ArrayList<Invoice>();
					invoicesMap.put(supplierCompnay, list);
				}
				list.add(invoice);
				System.out
						.println("[COMPANY_ID, INVOICE_NUMBER, EXPECTED_PAYMENT_DATE, CURRENT_DATE] => ["
								+ companyId
								+ ", "
								+ invoice.getInvoiceNumber()
								+ ", "
								+ expectedPaymentDate
								+ ", "
								+ currentDate + "]");
			}
		}

		System.out.println("End of invoices for company id " + companyId);
	}
}
